package com.rankeiot.platform.service;

import com.rankeiot.core.util.CollectionUtil;
import com.rankeiot.platform.domain.Role;
import com.rankeiot.platform.domain.RolePermission;
import com.rankeiot.platform.domain.UserRole;

import lombok.RequiredArgsConstructor;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 角色服务
 * @author desire
 */
@Service
@RequiredArgsConstructor
public class RoleService {

    final SqlToyLazyDao dao;

    public Set<String> getPermissionOfRole(String role){
        RolePermission query=new RolePermission();
        query.setRole(role);
        List<RolePermission> permissions= dao.findBySql("select * from "+RolePermission.TABLE+" where role=:role",query);
        return CollectionUtil.mapToSet(permissions, RolePermission::getPermission);
    }
    public Set<String> getPermissionOfUser(String username){
        RolePermission query=new RolePermission();
        query.setRole(username);
        List<RolePermission> permissions= dao.findBySql("select DISTINCT(a.permission)  permission from t_role_permission a INNER JOIN t_user_role b on a.role=b.role where b.user_name=:role",query);
        return CollectionUtil.mapToSet(permissions,RolePermission::getPermission);
    }
    public Set<String> getRoleSetOfUser(String username){
        List<UserRole> permissions= dao.findBySql("select role from t_user_role  where user_name=:username",new UserRole(username));
        return CollectionUtil.mapToSet(permissions, UserRole::getRole);
    }

    public List<Role> getRoleOfUser(String username){
        Role role=new Role();
        role.setName(username);
        return dao.findBySql("select r.* from t_user_role ur INNER JOIN t_role r ON ur.role=r.sn  where ur.user_name=:name",role);
    }
    public Set<String> getAllRole(){
        List<Role> roles=dao.findBySql("select * from t_role",new Role());
        return CollectionUtil.mapToSet(roles, Role::getSn);
    }

    /**
     * 删除用户原有的role,新增指定roles
     * @param username 用户名
     * @param roles 角色列表
     */
    @Transactional
    public void updateRolesOf(String username, Collection<String> roles) {
       dao.executeSql("delete from t_user_role where user_name=:username",new UserRole(username));
       List<UserRole> addUserRoles= CollectionUtil.map(roles,role->new UserRole(username,role));
       dao.saveAll(addUserRoles);
    }
}
